package com.fz.us.oa.web.controller.common;

import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.utils.DocConverterUtil;
import com.fz.us.admin.base.utils.LogUtil;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mongodb.gridfs.GridFSDBFile;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * 控制器 - 文件上传、读取等操作
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author henryxu
 * @version 1.0 2016-12-13 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/common/file")
public class FileController extends BaseController {

    private static final long serialVersionUID = 6492999494608560329L;

    @Autowired
    private FileManagerService fileManageService;

    //上传文件使用
    protected File filedata;
    protected String filename;
    protected String filedataFileName;
    protected String filedataContentType;

    /**
     * 上传文件
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        LogUtil.debug("进入/common/file/upload方法！");

        Result result = null;

        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() != ""){
                        System.out.println(myFileName);

                        Map<String, Object> data = new HashMap<String, Object>();
                        FileManage fileManage = fileManageService.gridFSSave(file.getInputStream(),"APPLICATION/OCTET-STREAM",myFileName);

                        data.put("fileId",fileManage.getId());
                        data.put("state",200);
                        data.put("name",fileManage.getName());
                        data.put("url",fileManage.getUrl());
                        data.put("msg", "上传成功");
                        result = resultService.successWithData(data);
                    }
                }
            }
        }

        if (result == null) {
            result = resultService.fail("上传文件失败");
        }

        return ajaxJson(result);
    }
    /**
     * 删除附件
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object delFile(@RequestParam() String keyId){
//        LogUtil.debug("进入/common/file/delete方法！");

        FileManage fileManage = fileManageService.get(keyId);
        fileManageService.delete(fileManage);

        Result result = resultService.success("删除成功！");
        return ajaxJson(result);
    }

    /**
     * 附件列表
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object fileList(@RequestParam(required = false) String keyId){
//        LogUtil.debug("进入/common/file/list方法！ keyId:" + keyId);

        Map<String, Object> data = new HashMap<String, Object>();
        ArrayList<Map<String,Object>> dataRows= Lists.newArrayList();
        Map<String,Object> rMap ;
        if(StringUtils.isNotEmpty(keyId)){
            for(String fileId : StringUtils.split(keyId, ",")){
                FileManage fileManage = fileManageService.get(fileId);
                if(fileManage == null){
                    continue;
                }
                rMap =  Maps.newHashMap();
                rMap.put("fileId",fileManage.getId());
                rMap.put("name",fileManage.getName());
                rMap.put("url",fileManage.getUrl());
                dataRows.add(JSONObject.fromObject(rMap));
            }
        }
        data.put("dataRows",dataRows);
        data.put("num",dataRows.size());
        Result result = resultService.successWithData(data);
        return ajaxJson(result);
    }

    /**
     * 附件下载
     * @return
     */
    @RequestMapping(value = "download", method = RequestMethod.GET)
    public Object download(@RequestParam() String gridId, HttpServletResponse response) throws IOException {
//        LogUtil.debug("进入/common/file/download！ gridId:" + gridId);

        GridFSDBFile file = fileManageService.gridFSGet(gridId);
        if(file == null) return null;
        OutputStream out = null;
        if(file.getContentType()!=null){
            response.setContentType(file.getContentType());
        }
        String suffix = file.getFilename().substring(file.getFilename().lastIndexOf("."),file.getFilename().length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" +new String(file.getFilename().getBytes() + suffix) + "\"");
        out = response.getOutputStream();
        file.writeTo(out);
        return null;
     //   return ajaxJson(resultService.success("下载成功"));
    }
    /**
     * 预览
     * @return
     */
    @RequestMapping(value = "view", method = RequestMethod.GET)
    public String view(@RequestParam() String gridId,Model model,HttpServletResponse response) throws IOException {
        GridFSDBFile file = fileManageService.gridFSGet(gridId);
        InputStream in = file.getInputStream();
        String arr[] = {".ppt",".pptx",".doc",".docx",".xls",".xlsx"};
        String suffix = file.getFilename().substring(file.getFilename().lastIndexOf("."),file.getFilename().length());
        String fileString = System.currentTimeMillis()+"";
        File dir = new File("/temp");
        if (!dir.exists()){
            dir.mkdirs();
        }
        File file2 = new File(dir,fileString+ suffix);
        FileOutputStream out = new FileOutputStream(file2);
        Streams.copy(in, out, true);
        if(!Arrays.asList(arr).contains(suffix)){
            response.sendRedirect("/temp/"+fileString+ suffix);
            return "";
        }
        String fileName= fileString+".swf";
        DocConverterUtil d = new DocConverterUtil("/temp/"+fileString+ suffix);
        model.addAttribute("filePath", "/temp/"+fileName);
        d.conver();
        return "/com/documentView";

    }


    /**
     * 下载
     */
    @RequestMapping(value = "ueditorDownload/{id}", method = RequestMethod.GET)
    public Object download(@PathVariable String id) throws IOException {
        if (StringUtils.isNotEmpty(id)) {
            FileManage fileManage = fileManageService.get(id);
            if (fileManage != null) {
                try {
                    GridFSDBFile file = fileManageService.gridFSGet(fileManage.getGridId());
                    if (file != null) {
                        return fileDownload(file.getInputStream(), file.getFilename());
                    }
                } catch (Exception e) {
                    LogUtil.error("FileController - download: "+e.toString());
                    return ajaxJson("{\"error\": \"下载文件发生异常\"}", HttpStatus.INTERNAL_SERVER_ERROR);
                }
            }
        }
        return ajaxJson("{\"error\": \"下载失败\"}", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
